#include "socket.h"

Socket::Socket(int port, std::string hostname)
{
    _mySocket = socket(AF_INET, SOCK_STREAM, 0);
    if( _mySocket < 0 ) shutdown( _mySocket, SHUT_RDWR);

    server = gethostbyname(hostname.c_str());
    if( server == NULL) shutdown( _mySocket, SHUT_RDWR);

    memset( (char*) &_serverAddress, '\0', sizeof(_serverAddress) );
    _serverAddress.sin_family = AF_INET;
    memcpy((char *)&_serverAddress.sin_addr.s_addr,
           (char *)server->h_addr,
           server->h_length);
    _serverAddress.sin_port = htons(port);

    setUsername("Cliente");
};

void Socket::connectSocket() {
    if( connect(_mySocket, (struct sockaddr*) &_serverAddress, sizeof(_serverAddress)) < 0)
        shutdown(_mySocket, SHUT_RDWR);
};

int Socket::sendMessage(std::string msg) {
    return send(_mySocket, msg.c_str(), msg.size(), 0);
};

int Socket::receiveMessage(std::string& msg) {
    char b[1024];
    bzero(b,1024);
    int a = recv(_mySocket, b, 1024, 0);
    in_buffer = std::string(b);
    msg = in_buffer;
    return a;
}

int Socket::operator >> (std::string& msg) {
    return receiveMessage(msg);
}

int Socket::operator << (std::string msg) {
    return sendMessage(msg);
}

int& Socket::operator () () {
    return _mySocket;
}
